<template>
  <HeaderBar
      :isFixed="true"
      title="申请退款"
      navBarBgc="linear-gradient(180deg, rgba(152,203,179,1) 0%, rgba(169,211,190,1) 29%, rgba(215,230,221,1) 74%);"
  ></HeaderBar>
  <view class="page-container">
    <view class="provider-container">
      <view class="provider-name-container flex items-center">
        <i class="iconfont icon-w_shangdian"></i>
        <text class="ml10 mr10 second-title">{{orderDetailObj.providerName}}</text>
        <i class="iconfont icon-jiantouyou"></i>
      </view>
      <view class="product-container flex items-start justify-between">
        <view class="product-img-container">
          <image class="product-img" :src="orderDetailObj.productImg"></image>
        </view>
        <view class="product-info-container">
          <view class="product-name-number-container flex items-center justify-between">
            <view class="product-name">{{orderDetailObj.productName}}</view>
            <view class="price ml20">{{orderDetailObj.price}}</view>
          </view>
          <view class="favor-number-container flex items-center justify-between">
            <view class="favor">{{orderDetailObj.typeName}}</view>
            <view class="number">X{{orderDetailObj.quantity}}</view>
          </view>
          <view class="specification-container">
            规格：{{orderDetailObj.typeName}}  规格：{{orderDetailObj.specsName}}
          </view>
        </view>
      </view>
    </view>
    <view class="after-sale-container">
      <view class="module-title">选择售后类型</view>
      <view class="after-sale-btn-container flex ">
        <view
            v-for="(item,index) in afterSaleList"
            :key="index"
            :class="['btn', afterSaleType === item.type ? 'active-btn' : '']"
            @click="afterSaleType = item.type"
        >
          {{item.label}}
        </view>
      </view>
    </view>
    <view class="cause-container">
      <view class="header-title pb10 flex items-center justify-between">
        <view class="title">退款金额</view>
        <view class="total-price">{{(orderDetailObj.price * orderDetailObj.quantity).toFixed(2)}}</view>
      </view>
      <view class="description-content">1-3 个工作日退还至原支付方，以实际退款金额为准</view>
      <wd-divider color="#C0C2B3" custom-class="custom-divider-class"></wd-divider>
      <view class="header-title flex items-center justify-between">
        <view class="title refund-case-title">退款原因</view>
        <view class="cause-choice-container flex items-center" @click="showRefundCasePopup = true">
          <text class="fs12-half">{{selectedCauseOptionObj.label || "请选择"}}</text>
          <wd-icon name="chevron-right" size="20px" color="#000000"></wd-icon>
        </view>
      </view>
      <wd-divider color="#C0C2B3" custom-class="custom-divider-class"></wd-divider>
      <view class="header-title flex items-center justify-between">
        <view class="title evidence-title">上传描述和凭证</view>
        <view class="cause-choice-container flex items-center" @click="showEvidencePopup = true">
          <text class="fs12-half brown">上传有助于处理退款</text>
          <wd-icon name="chevron-right" size="20px" color="#000000"></wd-icon>
        </view>
      </view>
      <wd-divider color="#C0C2B3" custom-class="custom-divider-class"></wd-divider>
      <view class="other-cause-title">
        其他原因
      </view>
      <view class="memo-container">
        <wd-textarea
            v-model="memo"
            placeholder="补充退款原因详情，有助于平台更好的为你服务"
            :maxlength="100"
            custom-class="custom-textarea-class"
        >
        </wd-textarea>
      </view>
    </view>
    <view class="foot-btn-container">
      <view class="bottom-content-container flex items-center justify-between">
        <view class="left-container">
          退款金额
          <view class="refund-total-price">{{(orderDetailObj.price * orderDetailObj.quantity).toFixed(2)}}</view>
        </view>
        <view class="operation-btn" @click="handleRefundAfterSales">提交</view>
      </view>
      <view class="safe-content" :style="{height: safeAreaBottom + 'px'}"></view>
    </view>
    <wd-popup
        v-model="showRefundCasePopup"
        position="bottom"
        custom-style="border-radius:12rpx"
    >
      <view class="custom-refund-cause-container">
        <view class="popup-header-container flex ">
          <view class="title flex-1">退款原因</view>
          <wd-icon name="close" size="18px" @click="showRefundCasePopup = false"></wd-icon>
        </view>
        <scroll-view :scroll-y="true" class="cause-option-container">
          <radio-group @change="changeCauseOption">
            <label
                v-for="(item, index) in causeOptionList"
                :key="index"
            >
              <view class="option-cell  flex items-center justify-between">
                <view class="label-content">{{item.name}}</view>
                <view>
                  <radio
                      :value="JSON.stringify({ value: item.id, label: item.name })"
                      :checked="item.id === selectedCauseOptionObj.value"
                      style="transform:scale(0.7)"
                  />
                </view>
              </view>
            </label>
          </radio-group>
        </scroll-view>
        <view class="confirm-btn" @click="handleConfirm">
          确定
        </view>
      </view>
    </wd-popup>
    <wd-popup
        v-model="showEvidencePopup"
        position="bottom"
        custom-style="border-radius:12rpx"
    >
      <view class="custom-refund-cause-container">
        <view class="popup-header-container flex ">
          <view class="title flex-1">上传描述和凭证</view>
<!--          <wd-icon name="close" size="18px" @click="showEvidencePopup = false"></wd-icon>-->
        </view>
        <view class="evidence-container">
<!--          <wd-textarea
              v-model="evidenceDescription"
              placeholder="补充描述，有助于商家更好的处理售后问题"
              custom-class="custom-text-area-class"
          />-->
          <wd-upload
              :file-list="evidenceFileList"
              accept="image"
              custom-class="custom-upload-class"
              :upload-method="handleUpdateImg"
              :multiple="false"
              :limit="3"
              :before-remove="beforeRemoveImg"
          >
            <view class="evidence-file-container flex flex-col items-center">
              <wd-icon name="camera" size="28px" color="#a7a7a7"></wd-icon>
              <view class="upload-description" >上传描述和凭证</view>
            </view>
          </wd-upload>
        </view>
        <view class="confirm-evidence-btn" @click="showEvidencePopup = false">
          完成
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
  import { ref, reactive } from "vue";
  import {orderDetail, uploadImg} from "@/api/common";
  import {useCommonData} from "@/hook/useCommonData";
  import {orderAfterSales} from "@/api/specialty";

  const { queryCommonArea } = useCommonData();

  const userId = ref("");
  const orderId = ref("");
  const afterSaleType = ref(1);
  const afterSaleList = ref([
    {type: 1, label: "仅退款"},
    {type: 2, label: "退货退款"},
  ]);
  const orderDetailObj = reactive({
    providerId: "",
    providerName: "",
    productId: "",
    productImg: "",
    productName: "",
    typeName: "",
    specsName: "",
    price: "",
    quantity: "",
    totalAmount: ""
  });
  const memo = ref("");
  const safeAreaBottom = ref(0);
  const showRefundCasePopup = ref(false);
  const causeOptionList = ref([
    { label: "计划有变没时间消费", value: 1 },
    { label: "买多了/买错了", value: 2 },
    { label: "担心安全问题(天气等)", value: 3 },
    { label: "后悔了，不想要了 ", value: 4 },
    { label: "误以为是外卖 ", value: 5 },
    { label: "没看清使用规则，要用时才发现限制多 ", value: 6 },
    { label: "其他平台/店里活动更优惠 ", value: 7 },
    { label: "预约不上/排队太久", value: 8 },
    { label: "联系不上商家", value: 9 },
    { label: "朋友/网上评价不好 ", value: 10 },
    { label: "商家要求改用其他方式/平台付款", value: 11 },
    { label: "商家营业但不接待", value: 12 },
    { label: "商家营业但不接待", value: 13 },
  ]);
  const selectedCauseOptionObj = reactive({
    label: "",
    value: ""
  });
  const currentSelectedCauseOptionObj = reactive({
    label: "",
    value: ""
  });
  const showEvidencePopup = ref(false);
  const evidenceDescription = ref("");
  const evidenceFileList = ref([]);

  const handleUpdateImg = (file,formData,options) => {
    console.log(file,'file');
    console.log(formData,'formData');
    console.log(options,'options');
    uni.downloadFile({
      url: file.url, // 图片的 URL
      success: (res) => {
        if (res.statusCode === 200) {
          // 下载成功，获取临时文件路径
          const tempFilePath = res.tempFilePath;

          // 如果需要进一步处理文件，可以使用 FileSystem API
          const fs = uni.getFileSystemManager(); // 注意：这里使用的是微信小程序的 API

          // 读取文件内容
          fs.readFile({
            filePath: tempFilePath,
            encoding: 'base64', // 或者 'binary' 用于获取二进制数据
            success: (readRes) => {
              uploadImg([{file:"image.png",base64:readRes.data}]).then(resFile => {
                let {uploadRes} = resFile;
                if(uploadRes && uploadRes.length > 0) {
                  let {path} = uploadRes[0];
                  if(path) {
                    evidenceFileList.value.push({path,url: file.url});
                    options.onSuccess(res, file, formData)
                  } else {
                    options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
                  }
                }
              })
            },
            fail: (err) => {
              options.onError(err, file, formData)
              console.error('读取文件失败:', err);
            }
          });
        } else {
          console.error('下载失败，状态码:', res.statusCode);
        }
      },
      fail: (err) => {
        options.onError(err, file, formData)
        console.error('下载失败:', err);
      }
    })
  };
  const beforeRemoveImg = (({ file, fileList, resolve }) => {
    let { url } = file;
    let index = evidenceFileList.value.findIndex(item => item.url === url);
    if(index !== -1) {
      evidenceFileList.value.splice(index, 1);
    }
    resolve(true);
  })
  const changeCauseOption = (event) => {
    console.log(event,'event');
    let { label, value } = JSON.parse(event.detail.value);
    currentSelectedCauseOptionObj.label = label;
    currentSelectedCauseOptionObj.value = value;
  };
  const handleConfirm = () => {
    let { label, value } = currentSelectedCauseOptionObj;
    if(!value) {
      uni.showToast({
        icon: "none",
        title: "请选择退款原因"
      });
      return;
    }
    selectedCauseOptionObj.value = value;
    selectedCauseOptionObj.label = label;
    showRefundCasePopup.value = false;
  };
  const handleRefundAfterSales = async () => {
    let tipContent = "";
    if(!selectedCauseOptionObj.label) {
      tipContent = "请选择退款原因";
    }
    if(evidenceFileList.value.length === 0) {
      tipContent = "请上传凭证";
    }
    if(tipContent) {
      uni.showToast({
        icon: "none",
        title: tipContent
      })
      return;
    }
    await orderAfterSales({
      orderId: orderId.value,
      userId: userId.value,
      remark: selectedCauseOptionObj.label,
      memo: memo.value,
      type: afterSaleType.value,
      urlList: evidenceFileList.value.map(item => item.path)
    }).then(res => {
      uni.showToast({
        icon: "none",
        title: "申请成功"
      })
      uni.navigateBack();
      console.log(res,'res');
    })
  };
  const queryOrderDetail = async () => {
    await orderDetail({orderId: orderId.value, userId: userId.value}).then(res => {
      let {
        merchantId,
        merchantName,
        productId,
        productName,
        productImg,
        typeName,
        specsName,
        price,
        quantity,
        totalAmount
      } = res.result;
      orderDetailObj.providerId = merchantId;
      orderDetailObj.providerName = merchantName;
      orderDetailObj.productId = productId;
      orderDetailObj.productImg = productImg;
      orderDetailObj.productName = productName;
      orderDetailObj.typeName = typeName;
      orderDetailObj.specsName = specsName;
      orderDetailObj.price = price;
      orderDetailObj.quantity = quantity;
      orderDetailObj.totalAmount = totalAmount;
    })
  }

  onLoad((options) => {
    let { orderId: _orderId } = options;
    orderId.value = _orderId;
    let {userId: _userId} = uni.getStorageSync("userInfo");
    userId.value = _userId;
    queryOrderDetail();
    safeAreaBottom.value = uni.getSystemInfoSync().safeAreaInsets.bottom;

    queryCommonArea("ORDER_MALL_RETURM").then((res)=>{
      let {result:ORDER_MALL_RETURM} = res;
      causeOptionList.value = ORDER_MALL_RETURM;
    })
  });
</script>

<style lang="scss" scoped>
  .page-container {
    height: calc(100vh - 142px);
    padding: 91px 28rpx 100rpx 28rpx;
    background: linear-gradient(180deg, rgba(197,223,209,1) 0%, rgba(239,239,237,1) 25%, rgba(239,239,237,1) 30%, rgba(239,239,237,1) 97%);

    .provider-container {
      margin: 27rpx 0;
      padding: 25rpx 29rpx;
      border-radius: 10rpx;
      background: #ffffff;
      .provider-name-container {
        .second-title {
          font-weight: bold;
          font-size: 29rpx;
        }
        .icon-w_shangdian {
          font-size: 46rpx;
          font-weight: bold;
          color: #1b9c61;
        }
        .icon-jiantouyou {
          font-size: 36rpx;
          font-weight: bold;
          color: #32322b;
        }
      }
      .product-container {
        box-sizing: border-box;
        margin-top: 26.5rpx;
        .product-img-container {
          width: 125rpx;
          height: 125rpx;
          border-radius: 10rpx;
          overflow: hidden;
          .product-img {
            width: 100%;
            height: 100%;
          }
        }
        .product-info-container {
          width: 76%;
          .product-name-number-container {
            width: 100%;
            .product-name {
              font-size: 25rpx;
              font-weight: bold;
              color: #2B2B24;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            .price {
              font-size: 22rpx;
              font-weight: bold;
            }
            .price:before {
              content: "￥";
              font-size: 20rpx;
            }
          }
          .favor-number-container {
            font-size: 22rpx;
            font-weight: 500;
            margin-top: 15.5rpx;
            color: #777777;
          }
          .specification-container {
            font-size: 22rpx;
            font-weight: 500;
            color: #777777;
          }
        }
      }
    }

    .after-sale-container {
      padding: 35rpx 28rpx;
      border-radius: 10rpx;
      background: #FFFFFF;
      .module-title {
        font-size: 29rpx;
        font-weight: bold;
      }
      .after-sale-btn-container {
        margin-top: 35rpx;
        .btn {
          margin-right: 35rpx;
          padding: 14rpx 64.5rpx;
          font-size: 29rpx;
          border-radius: 10rpx;
          border: 1px solid #C0C2B3;
          font-weight: bold;
          background: #EFEFED;
        }
        .btn:last-child {
          margin-right: 0;
        }
        .active-btn {
          color: #EEF0DF;
          background: #1B9C61;
        }
      }
    }

    .cause-container {
      margin-top: 28rpx;
      padding: 32rpx 28rpx 62rpx 28rpx;
      border-radius: 10rpx;
      background: #FFFFFF;
      .header-title {
        padding: 30rpx 0;
        .title {
          font-size: 29rpx;
          font-weight: bold;
        }
        .refund-case-title:after {
          content: "*";
          color: #AF5F25;
        }
        .evidence-title {
          color: #AF5F25;
        }
        .evidence-title:after {
          content: "*";
        }
        .total-price {
          font-size: 29rpx;
          font-weight: bold;
          color: #AA5413;
        }
        .total-price:before {
          content: "￥";
          font-size: 22rpx;
        }
      }
      .description-content {
        padding: 0 0 20rpx 0;
        font-size: 22rpx;
        color: #777777;
      }
      .other-cause-title {
        font-size: 29rpx;
        font-weight: bold;
        padding: 34rpx 0 24.5rpx 0;
      }
      .memo-container {
        height: 160rpx;
        border-radius: 30rpx;
        padding: 20rpx;
        border: 1px solid #A7A7A7;
        overflow: hidden;
      }
    }

    .foot-btn-container {
      box-sizing: border-box;
      position: fixed;
      width: 100%;
      left: 0;
      bottom: 0;
      padding: 28rpx 28rpx 0 28rpx;
      background: #EEF0DF;
      .bottom-content-container {
        .left-container {
          display: flex;
          align-items: baseline;
          font-size: 29rpx;
          .refund-total-price {
            font-size: 51.5rpx;
            font-weight: bold;
            color: #AA5413;
          }
          .refund-total-price:before {
            content: "￥";
            font-size: 25rpx;
          }
        }
        .operation-btn {
          padding: 14rpx 69.5rpx;
          font-size: 29rpx;
          border-radius: 10rpx;
          color: #EEF0DF;
          background: #1B9C61;
        }
      }
    } 

    :deep(.custom-divider-class) {
      padding: 0!important;
      margin: 0 !important;
    }
    :deep(.custom-textarea-class) {
      padding: 0!important;
      min-height: 160rpx !important;
    }
    .custom-refund-cause-container {
      position: relative;
      height: 1000rpx;
      background: linear-gradient(180deg, rgba(209,236,218,1) 0%, rgba(243,250,245,1) 13%, rgba(255,255,255,1) 100%);
      .popup-header-container {
        padding: 42rpx 28rpx;
        .title {
          font-size: 29rpx;
          font-weight: bold;
          text-align: center;
        }
      }
      .evidence-container {
        margin: 0 28rpx;
        padding: 44rpx 27rpx 0 27rpx;
        border-radius: 10rpx;
        background-color: #fff;
        .evidence-file-container {
          margin-top: 40rpx;
          padding: 64rpx 0 53rpx 0;
          width: calc(100vw - 14vw);
          border-radius: 10rpx;
          border: 1px dashed #A7A7A7;
          .upload-description {
            padding-top: 10rpx;
            font-size: 22rpx;
            color: #A7A7A7;
          }
        }
      }
      .confirm-evidence-btn {
        position: absolute;
        bottom: 40rpx;
        width: 667rpx;
        left: 50%;
        margin-left: -353rpx;
        padding: 21.5rpx;
        border-radius: 10rpx;
        text-align: center;
        font-size: 29rpx;
        color: #FDFFEB;
        background: #1B9C61;
      }
      .cause-option-container {
        box-sizing: border-box;
        padding: 0 56.5rpx;
        height: 740rpx;
        white-space: nowrap;
      }
      .confirm-btn {
        margin: 20rpx 28rpx 0 28rpx;
        text-align: center;
        padding: 21.5rpx;
        font-size: 29rpx;
        border-radius: 10rpx;
        color: #FDFFEB;
        background: #1B9C61;
      }
    }
    .option-cell {
      padding: 24rpx 0;
      border-bottom: 1rpx solid #C0C2B3;
      .label-content {
        font-size: 25rpx;
        color: #2B2B24;
      }
    }
    :deep(.custom-text-area-class) {
      padding: 0 !important;
      .wd-textarea__value {
        height: 100rpx !important;
      }
    }
  }
</style>